package com.listeningframework.boot.autoconfigure.security.overrides;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.listeningframework.boot.commons.http.HttpWebUtils;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

/**
 * 
 * Spring Security Ajax Session validate
 *
 * @author lixining
 * @version $Id: ListeningLoginUrlAuthenticationEntryPoint.java, v 0.1
 *          2016年1月28日 下午2:28:16 lixining Exp $
 */
public class AjaxLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {

	public AjaxLoginUrlAuthenticationEntryPoint(String loginFormUrl) {
		super(loginFormUrl);
	}

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {
		if (!HttpWebUtils.isAjaxRequest(request)) {
			super.commence(request, response, authException);
			return;
		}
		HttpWebUtils.allowCorsOnce(request, response);
		if (authException instanceof InsufficientAuthenticationException) {
			HttpWebUtils.writeJson(response, false, "403");
			return;
		}
		HttpWebUtils.writeJson(response, false, "timeout");
	}

}
